import {LuckyWheel} from 'lucky-canvas'

const table = document.getElementById("lucky-wheel-config");

const left = document.getElementById('left')

const colors = ['#b8c5f2', '#e9e8fe', '#e9e800']

// 创建 LuckyWheel 转盘对象
const luckyWheel = createLuckyWheel()

// 初始化
init()

function init() {
    // 防抖定时器
    let timer;
    // 初始化转盘宽高
    setLuckyWheelSize(luckyWheel)
    // 监听窗口伸缩
    window.addEventListener('resize', function () {
        setLuckyWheelSize(luckyWheel)
    })

    let inputs = table.querySelectorAll('input[type="text"]')

    inputs && inputs.forEach((input, index) => {
        input.addEventListener('input', function () {
            if (timer) {
                clearTimeout(timer)
            }
            timer = setTimeout(() => {
                luckyWheel.prizes = getLuckyWheelItems(getOptions())
            }, 500)
        })

        input.addEventListener('keydown', function (event) {
            if (event.key === 'Enter') {
                event.preventDefault();
                let nextCell = findNextCell(input.parentNode);
                nextCell && nextCell.querySelector('input').focus()
            }
        });
    })

    window.api.changeFontSize((event, fontSize) => {
        let prizes = luckyWheel.prizes
        prizes && prizes.forEach(prize => {
            prize.fonts[0].fontSize = fontSize + 'px'
        })
    })
}


function findNextCell(currentCell) {
    // 判断当前单元格是否在表格中
    if (currentCell && currentCell.tagName === 'TD') {
        // 当前单元格所在的 tr
        let currentRow = currentCell.parentElement;
        // 获取下一行 tr
        let nextRow = currentRow.nextElementSibling;
        // 获取当前单元格的列索引
        let cellIndex = Array.from(currentRow.children).indexOf(currentCell);
        if (nextRow) {
            // 获取下一个行的对应列的单元格
            return nextRow.children[cellIndex]
        } else {
            let firstRow = currentRow.parentNode.querySelector('tr');
            return currentRow.children[cellIndex + 1] ? firstRow.children[cellIndex + 1] : firstRow.children[cellIndex - 1]
        }
    } else {
        throw new Error('Please input a valid td element')
    }
}

function getOptions() {
    let tbody = table.getElementsByTagName('tbody')[0];
    let options = []
    let rows = tbody.querySelectorAll('tr');
    rows && rows.forEach(row => {
        let cells = row.querySelectorAll('td');
        if (!cells[1].classList.contains('disabled')) {
            if (cells.length === 3) {
                let value = cells[1].querySelector('input').value;
                let weight = cells[2].querySelector('input').value;
                if (value.length || weight.length) {
                    if (!weight.length) {
                        weight = 1
                    }
                    options.push({value, weight})
                }
            }
        }
    })
    return options
}

// 初始化或更改转盘宽高
function setLuckyWheelSize(luckyWheel) {
    const rect = left.getBoundingClientRect();
    const width = rect.width;
    const height = rect.height;
    const min = Math.min(width, height) * 0.9;
    luckyWheel.width = min + 'px'
    luckyWheel.height = min + 'px'
}


function findColor(before, after) {
    for (let color of colors) {
        if (color !== before && color !== after) {
            return color;
        }
    }
}

function getLuckyWheelItems(options) {
    let items = [];
    for (let option of options) {
        let item = {background: '', fonts: [{text: option.value, top: '10px', fontSize: '18px'}]}
        if (!items.length) {
            item.background = colors[0]
        }
        if (items.length) {
            let before = items[0].background;
            let after = items[items.length - 1].background;
            item.background = findColor(before, after)
        }
        for (let i = 0; i < option.weight; i++) {
            items.push(item)
        }
    }
    return items
}

function createLuckyWheel() {
    const luckyWheel = new LuckyWheel('#lucky-wheel', {
        width: '0px',
        height: '0px',
        blocks: [{padding: '10px', background: '#869cfa'}],
        prizes: [],
        buttons: [
            {radius: '40%', background: '#617df2'},
            {radius: '35%', background: '#afc8ff'},
            {
                radius: '30%', background: '#869cfa',
                pointer: true,
                fonts: [{text: '开始', top: '-10px'}]
            },
        ],
        start: function () {
            // 开始游戏
            luckyWheel.play()
            // 假设接口的请求速度是1s
            setTimeout(_ => {
                // 停止游戏
                let index = getRandomInt(0, 10000) % getItemCount();
                luckyWheel.stop(index)
            }, 1000)
        },
        end: function (item) { // 游戏停止时触发
            console.log(window)
            window.api.openMessageBox(item.fonts[0].text)
        }
    })
    return luckyWheel
}

//重置
window.reset = function reset() {
    let tbody = table.getElementsByTagName('tbody')[0];
    let rows = tbody.rows;
    for (let row of rows) {
        let cells = row.querySelectorAll('td');
        for (let i = 0; i < cells.length; i++) {
            let input = cells[i].querySelector('input');
            if (i === 0) {
                input.checked = false
            } else {
                input.value = ''
            }
        }
    }
    luckyWheel.prizes = []
}

window.addRow = function addRow() {
    let tbody = table.getElementsByTagName('tbody')[0];
    // 创建新的行
    const newRow = tbody.insertRow();
    for (let i = 0; i < 3; i++) {
        let cell = newRow.insertCell(i);
        const input = document.createElement('input');
        if (i === 0) {
            input.type = 'checkbox'
            input.classList.add('checkbox')
        } else {
            input.type = 'text'
            input.addEventListener('input', function () {
                luckyWheel.prizes = getLuckyWheelItems(getOptions())
            })
            input.addEventListener('keydown', function (event) {
                if (event.key === 'Enter') {
                    event.preventDefault();
                    let nextCell = findNextCell(input.parentNode);
                    nextCell && nextCell.querySelector('input').focus()
                }
            });
        }
        cell.appendChild(input);
    }
}


window.deleteRow = function deleteRow() {
    let tbody = table.getElementsByTagName('tbody')[0];
    let inputs = tbody.querySelectorAll('input:checked');
    inputs && inputs.forEach(input => {
        let row = input.parentNode.parentNode;
        row.parentNode.removeChild(row)
    })
    luckyWheel.prizes = getLuckyWheelItems(getOptions())
}


window.hideRow = function hideRow() {
    let tbody = table.getElementsByTagName('tbody')[0];
    let checkeds = tbody.querySelectorAll('input[type="checkbox"]:checked');
    let uncheckeds = tbody.querySelectorAll('input[type="checkbox"]:not(:checked)');
    checkeds && checkeds.forEach(input => {
        let row = input.parentNode.parentNode;
        let cells = row.querySelectorAll('td');
        for (let i = 1; i < cells.length; i++) {
            let cell = cells[i];
            let input = cells[i].querySelector('input');
            if (!cell.classList.contains('disabled')) {
                cell.classList.add('disabled')
                input.classList.add('disabled')
            }
        }
    })
    uncheckeds && uncheckeds.forEach(input => {
        let row = input.parentNode.parentNode;
        let cells = row.querySelectorAll('td');
        for (let i = 1; i < cells.length; i++) {
            let cell = cells[i];
            let input = cells[i].querySelector('input');
            if (cell.classList.contains('disabled')) {
                cell.classList.remove('disabled')
                input.classList.remove('disabled')
            }
        }
    })
    luckyWheel.prizes = getLuckyWheelItems(getOptions())
}

function getItemCount() {
    let count = 0;
    let rows = table.getElementsByTagName('tbody')[0].rows;
    for (let row of rows) {
        let value = row.querySelectorAll('td')[1].querySelector('input').value;
        let weight = row.querySelectorAll('td')[2].querySelector('input').value;
        if (value.length) {
            weight ? count += Number.parseInt(weight) : count += 1
        }
    }
    return count
}

/**
 * 生成指定范围内的随机整数
 * @param {number} min - 范围的最小值（包含）
 * @param {number} max - 范围的最大值（包含）
 * @returns {number} - 生成的随机整数
 */
function getRandomInt(min, max) {
    min = Math.ceil(min); // 向上取整
    max = Math.floor(max); // 向下取整
    return Math.floor(Math.random() * (max - min + 1)) + min; // 生成随机整数
}
